package com.db.mylogger;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class FileAppender implements IAppender {
	
	PrintWriter writer;
	private final ExecutorService executor;
	
	public FileAppender(String filename, boolean append) throws IOException {
		writer = new PrintWriter(new FileWriter(filename, append));
		executor = Executors.newSingleThreadExecutor();
	}

	@Override
	public void append(final String message) {
		executor.execute(new Runnable() {
			@Override 
			public void run() {
				writer.println(message);
				writer.flush();
			}
		});
	}

	@Override
	public void close() {
		executor.shutdown();
		try {
			executor.awaitTermination(1000,TimeUnit.MILLISECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		writer.close();
	}
}